package com.assess.web.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.assess.web.dao.AssessmentMapper;
import com.assess.web.model.Assessment;
import com.assess.web.model.AssessmentExample;
import com.assess.web.service.AddressService;
import com.assess.web.service.AssessmentService;
import com.assess.web.service.CompanyService;
import com.assess.web.util.DateUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AssessmentServiceImpl implements AssessmentService {
    @Autowired
    private AssessmentMapper assessmentMapper;
    @Autowired
    private AddressService addressService;
    @Autowired
    private CompanyService companyService;

    @Override
    public JSONObject page(Integer companyId, int pageNum, int pageSize) {
        AssessmentExample example = new AssessmentExample();
        if (null != companyId) {
            example.createCriteria().andCompanyIdEqualTo(companyId);
        }
        Page page = PageHelper.startPage(pageNum, pageSize, true);
        List<Assessment> list = assessmentMapper.selectByExample(example);
        JSONObject object = new JSONObject();
        object.put("code", 0);
        object.put("msg", "");
        object.put("count", page.getTotal());
        object.put("pages", page.getPageSize());
        object.put("pageNum", page.getPageNum());
        object.put("pageSize", pageSize);
        JSONArray jsonArray = new JSONArray();
        for (Assessment assessment : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", assessment.getId());
            jsonObject.put("address", addressService.getAddress(assessment.getAddressId()).getName());
            jsonObject.put("companyName", companyService.getCompany(assessment.getCompanyId()).getName());
            jsonObject.put("assessmentTime", DateUtil.format(assessment.getAssessmentTime()));
            jsonObject.put("createTime", DateUtil.format(assessment.getCreateTime()));
            jsonArray.add(jsonObject);
        }
        object.put("data", jsonArray);
        return object;
    }

    @Override
    public Assessment getAssessment(int id) {
        return assessmentMapper.selectByPrimaryKey(id);
    }

    @Override
    public int save(Assessment assessment) {
        return assessmentMapper.insertSelective(assessment);
    }

    @Override
    public int update(Assessment assessment) {
        return assessmentMapper.updateByPrimaryKeySelective(assessment);
    }
}
